package com.example.lib_common.utils

import com.google.gson.Gson
import com.tencent.mmkv.MMKV

object MMKVUtil {

    private val defaultKv: MMKV by lazy { MMKV.defaultMMKV() }
    private lateinit var kv: MMKV
    fun <T> set(key: String, value: T, kvId: String? = null): Boolean {
        kv = if (kvId.isNullOrEmpty()) defaultKv else MMKV.mmkvWithID(kvId, MMKV.SINGLE_PROCESS_MODE)
        return when (value) {
            is String -> kv.encode(key, value)
            is Int -> kv.encode(key, value)
            is Boolean -> kv.encode(key, value)
            is Long -> kv.encode(key, value)
            is Float -> kv.encode(key, value)
            is Double -> kv.encode(key, value)
            is ByteArray -> kv.encode(key, value)
            is Set<*> -> {
                kv.encode(key, value as Set<String>)
            }

            else -> kv.encode(key, Gson().toJson(value))
        }
    }

    fun <T> get(key: String, default: T, kvId: String? = null): T {
        kv = if (kvId.isNullOrEmpty()) defaultKv else MMKV.mmkvWithID(kvId, MMKV.SINGLE_PROCESS_MODE)
        val result: Any? = when (default) {
            is String -> kv.decodeString(key, default)
            is Int -> kv.decodeInt(key, default)
            is Boolean -> kv.decodeBool(key, default)
            is Long -> kv.decodeLong(key, default)
            is Float -> kv.decodeFloat(key, default)
            is Double -> kv.decodeDouble(key, default)
            is ByteArray -> kv.decodeBytes(key) ?: default
            is Set<*> -> kv.decodeStringSet(key, default as Set<String>)
            else -> {
                val json = kv.decodeString(key, "")
                if (!json.isNullOrEmpty()) Gson().fromJson(json, default!!::class.java) else null
            }
        }
        return (result as? T) ?: default
    }
}
